﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MossmanMill.DataModel;
using System.Drawing;
using MossmanMill.View;
using MossmanMill.Properties;

namespace MossmanMill
{
    partial class MainForm
    {
        private Rack selectedRack;
        private Slottable[] rackCards;
        private Point rackDrawOffset;
        private StringFormat verticalText;
        private int freeSpace;
        private Rectangle backRect, cardRect;

        private void initRack(Rack rack)
        {
            level = Level.RACK;
            selectedRack = rack;
            rackCards = new Slottable[13];
            verticalText = new StringFormat(StringFormatFlags.DirectionVertical);
            var cards = db.GetSlottables(rack);
            foreach (var card in cards)
            {
                rackCards[card.Position] = card;
            }
            rackDrawOffset = new Point((viewPanel.Width - 600) / 2, 100);
            freeSpace = countFreeSpace(rackCards);
            if (selectedRoom == null) selectedRoom = db.GetRoom(rack.RoomId);
            backRect = new Rectangle(0, viewPanel.Height - 30, 90, 30);
            cardRect = new Rectangle(rackDrawOffset.X, rackDrawOffset.Y + 120, 40 * 15, 80);
            menuEditDataInput.Enabled = true;
            menuEditDragDrop.Enabled = true;
        }

        private int countFreeSpace(Slottable[] cards)
        {
            int count = 0;
            for (int i = 0; i < cards.Length; i++)
            {
                if (cards[i] == null)
                {
                    count++;
                    continue;
                }
                if (cards[i].SlotType == 'P') i++;
            }
            return count;
        }

        private void DrawRack(Graphics g)
        {
            g.DrawString(selectedRoom.Name, Fonts.largeArial, Brushes.Black, rackDrawOffset.X, 5);
            selectedRack.draw(g, rackDrawOffset.X, rackDrawOffset.Y, 1.0f, true);
            
            DrawBackButton(g);
        }

        private void ClickRack(Point c, int type)
        {
            if (selectedRack.interact(c, type, rackDrawOffset.X, rackDrawOffset.Y, 1.0f, true)) viewPanel.Invalidate();
            selectedSlottable = selectedRack.SelectedCard;
            if (selectedSlottable != null && selectedSlottable.SlotType == 'C') selectedCard = (Card)selectedSlottable;
            if (backRect.Contains(c) && type == 2)
            {
                selectedCard = null;
                InitRoom();
                viewPanel.Invalidate();
                return;
            }
        }

    }
}
